<template>
    <div class="login-container">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即登录</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
    import {postRequest} from '../util/api'
    export default {
        data() {
        return {
            ruleForm: {
                username: '',
                password: ''
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 8, max: 12, message: '长度在 8 到 12 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 8, max: 28, message: '长度在 8 到 20 个字符', trigger: 'blur' }
                ],
            }
        };
        },
        methods: {
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                if (valid) {
                    var _this = this;
                    this.loading = true;
                    postRequest('/login', {
                    username: this.ruleForm.username,
                    password: this.ruleForm.password
                    }).then(resp=> {
                        _this.loading = false;
                        if (resp.status == 200) {
                            //成功
                            var json = resp.data;
                            if (json.status == 'success') {
                                _this.$router.replace({path: '/home'});
                            } else {
                                _this.$alert('登录失败!', '失败!');
                            }
                        } else {
                            //失败
                            _this.$alert('登录失败!', '失败!');
                        }
                    });
                } else {
                    return false;
                }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            }
        }
    }
</script>
<style>
    .login-container {
        border-radius: 15px;
        background-clip: padding-box;
        margin: 130px auto;
        width: 350px;
        padding: 55px 55px 15px 35px;
        background: #fff;
        border: 1px solid #eaeaea;
        box-shadow: 0 0 25px #cac6c6;
    }
</style>